import { fromJS } from 'immutable'

import { WS_SEND_DATA } from '../middleware/ws'

import { TRADE_MARKET_ACTION } from '../reducers/tradeMarketReducer'
import { TRADE_BID_ASK_ACTION } from '../reducers/tradeBidAskReducer'
import { TRADE_DEAL_DETAIL_ACTION } from '../reducers/tradeDealDetailReducer'

import { getContractInfo } from '../../api/contractApi'
import { formatValue } from '../../utils/dataUtils'

/**
 * 查询合约信息
 * @returns {function(...[*]=)}
 */
export function queryContractInfo () {
  const contractCode = localStorage.getItem('contract_code')
  return dispatch => {
    getContractInfo().then(
      result => {
        if (result) {
          const data = result.data || []
          const contracts = {}
          let currentContract = data[0]
          data.forEach(contract => {
            if (contractCode === contract.InstrumentID) {
              currentContract = contract
            }
            contracts[contract.InstrumentID] = contract
          })
          localStorage.setItem('contract_code', currentContract.InstrumentID)
          dispatch({
            type: TRADE_MARKET_ACTION,
            data: {
              contracts: fromJS(contracts),
              contractList: fromJS(data),
              currentContract: fromJS(currentContract)
            }
          })
        }
      }
    ).catch(_ => {})
  }
}

/**
 * 设置合约
 * @param contract
 */
export function setContract (contract) {
  return (dispatch, getState) => {
    const currentContract = getState().trade.market.get('currentContract')
    if (formatValue(contract, 'InstrumentID') !== formatValue(currentContract, 'InstrumentID')) {
      localStorage.setItem('contract_code', formatValue(contract, 'InstrumentID'))
      const empty = fromJS([])
      dispatch({
        type: TRADE_BID_ASK_ACTION,
        data: {
          totalBid: fromJS({}),
          totalAsk: fromJS({}),
          bidList: empty,
          askList: empty
        }
      })
      dispatch({
        type: TRADE_DEAL_DETAIL_ACTION,
        data: {
          dealDetail: empty
        }
      })
      dispatch({
        type: TRADE_MARKET_ACTION,
        data: {
          currentContract: contract
        }
      })
    }
  }
}

/**
 * 订阅行情
 * @param contract
 * @returns {function(...[*]=)}
 */
export function subscribeMarket (contract) {
  return dispatch => {
    if (contract) {
      dispatch({
        type: WS_SEND_DATA,
        data: {
          SendTopicAction: {
            Action: '1',
            LocalNo: 2,
            TopicID: '2',
            FilterValue: `${formatValue(contract, 'ExchangeID')}_${formatValue(contract, 'InstrumentID')}`,
            ResumeNo: -1
          }
        }
      })
    }
  }
}

/**
 * 取消行情订阅
 * @param contract
 * @returns {{data: {fid: string, id: string}, type: string}}
 */
export function unsubscribeMarket (contract) {
  return dispatch => {
    if (contract) {
      dispatch({
        type: WS_SEND_DATA,
        data: {
          SendTopicAction: {
            Action: '2',
            LocalNo: 2,
            TopicID: '2',
            FilterValue: `${formatValue(contract, 'ExchangeID')}_${formatValue(contract, 'InstrumentID')}`,
            ResumeNo: -1
          }
        }
      })
    }
  }
}
